# -*- coding: utf-8 -*-
from flask import Flask
from flask_mail import Mail
from flask_wtf import CsrfProtect
from apps import models
from apps.ext import init_db, init_session, init_admin, init_uploads_config
from apps.index.views import index as index_blueprint
from apps.kind.views import kind as kind_blueprint
from apps.news.views import news as news_blueprint
from apps.echarts.views import data as data_blueprint
from apps.account.views import account as account_blueprint
from celery import Celery

app = Flask(__name__)


def create_app():
    """
    注册app模块
    :return:
    """
    app.debug = True
    create_blueprint(app)
    init_db(app)
    CsrfProtect(app)
    init_session(app)
    init_admin(app)
    init_api(app)
    init_uploads_config(app)
    return app


# -------------------------------Mail配置--------------------------------
app.config['MAIL_SERVER'] = 'smtp.163.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USERNAME'] = 'wang_call_test@163.com'
app.config['MAIL_PASSWORD'] = "wy1363484499"
app.config['MAIL_DEFAULT_SENDER'] = 'wang_call_test@163.com'
mail = Mail(app)
# ---------------------- Celery配置  begin-----------------------
app.config['CELERY_RESULT_BACKEND'] = "redis://127.0.0.1:6379/1"
app.config['CELERY_BROKER_URL'] = "redis://127.0.0.1:6379/1"

celery = Celery(app.name, backend=app.config['CELERY_RESULT_BACKEND'],
                broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)


@celery.task
def send_async_email(message):
    """
    异步邮件发送
    :param message:
    :return:
    """
    with app.app_context():
        mail.send(message)


# ---------------------- Celery配置  end-----------------------


def create_blueprint(app):
    """
    注册蓝图对象
    :param app:
    :return:
    """
    app.register_blueprint(index_blueprint)
    app.register_blueprint(kind_blueprint)
    app.register_blueprint(news_blueprint, url_prefix="/news")
    app.register_blueprint(data_blueprint, url_prefix="/data")
    app.register_blueprint(account_blueprint, url_prefix="/account")


# --------------------------------------配置api路由----------------------------------
from flask_restful import Api

from apps.apis.views import HomeApi, CatApi, DetailApi

api = Api(prefix='/api')


def init_api(app):
    api.init_app(app)


api.add_resource(HomeApi, '/index/')
api.add_resource(CatApi, '/kind/')
api.add_resource(DetailApi, '/news/')
